package application.decryption;

import java.util.Vector;

import javax.swing.JTextArea;

import dao.TxtFileReader;

public class DecryptedInfo3 implements Decryption {
    public static final String CAESEA = "Caesar";
    private TxtFileReader reader = new TxtFileReader();

    @Override
    public void log(JTextArea txtArea) {
        Vector<String> cipherLines = reader.readCiphers(CAESEA);
        int num = cipherLines.size();
        txtArea.append("Decrypting data in " + CAESEA + ".txt ...\n");

        for (String line : cipherLines) {
            line = line.trim();
            if (line.equals("")) {
                continue;
            }

            String[] s = line.split(" ");
            String lastName = decryptName(s[0]);
            String firstName = decryptName(s[1]);
            String code = decryptCode(s[2]);

            txtArea.append("Decrypted No." + num-- + " agent info: \n");

            txtArea.append("Decrypt first name from " + s[1] + " to " + firstName + "\n");
            txtArea.append("Decrypt last name from " + s[0] + " to " + lastName + "\n");
            txtArea.append("Decrypt agent code name from " + s[2] + " to " + code + "\n\n");
        }
        txtArea.append("All agent info in " + CAESEA + ".txt has been decrypted\n\n");
    }

    @Override
    public String decryptName(String cipher) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < cipher.length(); ++i) {
            buffer.append(decrypt(cipher.charAt(i)));
        }

        return buffer.toString();
    }

    @Override
    public String decryptCode(String cipher) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < cipher.length(); ++i) {
            buffer.append(decrypt(cipher.charAt(i)));
        }

        return buffer.toString();
    }

    private char decrypt(char ch) {
        if (Character.isUpperCase(ch)) {
            int x = ch - 'A' - 1;

            if (x < 0) {
                x += 26;
            }

            return (char) (x % 26 + 'A');
        }

        if (Character.isLowerCase(ch)) {
            int x = ch - 'a' - 1;

            if (x < 0) {
                x += 26;
            }

            return (char) (x % 26 + 'a');
        }

        if (Character.isDigit(ch)) {
            int x = ch - '0' - 1;

            if (x < 0) {
                x += 10;
            }

            return (char) (x % 10 + '0');
        }

        return ch;
    }
}
